package kaalanshare;

import java.io.*;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * User: twin
 * Date: 26.04.12
 * Time: 20:48
 * To change this template use File | Settings | File Templates.
 */
public class FileReceiver {
    public static boolean dataInputStreamRead(Socket sock) throws IOException {
        int bytesRead = 0;
        InputStream in = null;
        try {
            in = sock.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        DataInputStream clientData = new DataInputStream(in);
        String fileName = null;
        try {
            fileName = clientData.readUTF();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if (fileName.equals("!!finished")) {
            System.out.println("finished receiving");

            return false;
        } else if (fileName.equals("!!no_File")) {
            System.out.println("no file " + fileName);
            return false;
        }
        String file2;
        if ((file2 = new File(fileName).getParent()) != null) {
            File file1 = new File(file2);
            file1.mkdirs();
        }

        System.out.println("retreiving:\t" + fileName);
        OutputStream output = new FileOutputStream(fileName);
        long size = clientData.readLong();
        byte[] buffer = new byte[1024];
        while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
        }

        // Closing the FileOutputStream handle
        output.close();
        return true;
    }

    public static void getFileFromHost(String address, String desiredfile) throws IOException {
        Socket socket = new Socket(address, 1992);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        //sending filename to server
        out.writeUTF(desiredfile);
        out.flush();
        try {
            while (dataInputStreamRead(socket)) {
            }
        } catch (EOFException ex) {
            System.out.println("conection terminated");
        } finally {
            socket.close();
        }
    }
}
